//
//  EmotionView.swift
//  表情键盘
//
//  Created by 李国伟 on 15/12/15.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit
let emotionCell = "emotionCell"
class EmotionView: UIView {
   
    private var finshedCallBack:(emotion: Emoticon) -> ()
    //设置布局
      init(CallBack:(emotion: Emoticon) -> ()) {
        finshedCallBack = CallBack
        let rect = CGRectMake(0, 0, 30, 226)
        super.init(frame: rect)
        setupUI()
        
        let indexpath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexpath, atScrollPosition: .Left, animated: false)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmotionLayout())
    
    //设置懒加载控件toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //设置模型数组
    let packages = EmoticonManager().emoticonPackage as! [EmoticonPackage]
    
    //自定义流水布局
    private class EmotionLayout: UICollectionViewFlowLayout{
        
        //重写parer for layout 方法,这里面可以拿到前后控件
        private override func prepareLayout() {
            
            //滚动方向，item大小，间隙，弹簧效果，取消滚动条,显示分页，设置上下的内间距
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.pagingEnabled = true
            
            let row:CGFloat = 3
            let col:CGFloat = 7
            let w = collectionView!.bounds.width / col
            itemSize = CGSizeMake(w, w)
            
            //设置上下间距
            let margin = (collectionView!.bounds.height - row * w) * 0.4999
            
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        }
    }
    
    //设置控件以及约束
    private func setupUI(){
        addSubview(collectionView)
        addSubview(toolBar)
        
        //设置约束
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self)
            make.right.equalTo(self)
            make.top.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self)
            make.right.equalTo(self)
            make.height.equalTo(44)
            make.bottom.equalTo(self)
        }
        
        
        prepareForCollectionView()
        prepareForToolBar()
    }
    
}

//MARK： 准备工作
extension EmotionView: UICollectionViewDataSource ,UICollectionViewDelegate{
    
    //设置数据源和代理
    private func prepareForCollectionView(){
        //注册可重用cell
        collectionView.registerClass(EmotionCell.self, forCellWithReuseIdentifier: emotionCell)
        collectionView.backgroundColor = UIColor(white: 0.9, alpha: 1)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    //添加几个按钮，弹簧效果
    private func prepareForToolBar(){
        toolBar.tintColor = UIColor.darkGrayColor()
        //设置几个按钮
        var items = [UIBarButtonItem]()
        var index = 0
        
        for d in packages {
            items.append(UIBarButtonItem(title: d.group_name_cn, style: .Plain, target: self, action: "clickItem:"))
            items.last?.tag = index
            index++
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil))
        }
       items.removeLast()
       toolBar.items = items
    }
    
    //点击item触发事件
    @objc private func clickItem(item: UIBarButtonItem) {
       let indexpath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexpath, atScrollPosition: .Left, animated: false)
    }
}

///MARK:  代理方法和数据源方法
extension EmotionView {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //取出对应的模型
        let emotionModel = packages[indexPath.section].emoticons[indexPath.row]
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emotionCell, forIndexPath: indexPath) as! EmotionCell
        cell.model = emotionModel as? Emoticon
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let model = packages[indexPath.section].emoticons[indexPath.row]
        finshedCallBack(emotion: model as! Emoticon)
    }
}

//自定义cell
private class EmotionCell: UICollectionViewCell{
    
    //设置数据
    var model: Emoticon?{
        didSet{
            
         emotionButton.setImage(UIImage(contentsOfFile: model!.imagePath), forState: .Normal)
            
        emotionButton.setTitle(model?.emoji, forState: .Normal)
          
          if model!.isRemove{
            emotionButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
         }
       }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        emotionButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emotionButton.userInteractionEnabled = false
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(emotionButton)
//        emotionButton.backgroundColor = UIColor.whiteColor()
        emotionButton.frame = CGRectInset(bounds, 4, 4)
        emotionButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    }
    
    //设置私有变量
    private lazy var emotionButton: UIButton = UIButton()
}